package com.ydx.demo.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin(origins = "*")
@Tag(name = "文件上传模块")
public class FileUploadController {

    /**
     * 处理文件上传请求
     *
     * @param uploadFiles 上传的文件数组
     * @return ResponseEntity<String> 返回文件上传结果
     */
    @PostMapping("/medicine/uploads")
    public ResponseEntity<Object> uploadFile(@RequestParam("uploadFiles") MultipartFile[] uploadFiles) {
        // 检查是否有文件被上传
        if (uploadFiles == null || uploadFiles.length == 0) {
            // 如果没有文件被上传，返回400错误
            return new ResponseEntity<>("请选择文件！", HttpStatus.BAD_REQUEST);
        }

        // 指定存储文件的根目录
        String uploadRootPath = "D:/photo/webImage";

        // 创建以当前日期为名称的文件夹
        String folderName = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        Path folderPath = Paths.get(uploadRootPath, folderName);
        try {
            Files.createDirectories(folderPath); // 创建文件夹
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("文件上传失败！", HttpStatus.INTERNAL_SERVER_ERROR);
        }

        // 用于保存上传成功的文件路径字符串数组
        List<String> filePaths = new ArrayList<>();

        // 循环上传文件
        for (MultipartFile uploadFile : uploadFiles) {
            String filename = uploadFile.getOriginalFilename();
            Path targetPath = folderPath.resolve(filename); // 目标文件路径
            try {
                uploadFile.transferTo(targetPath.toFile()); // 将上传的文件保存到目标文件
                System.out.println("文件上传成功：" + targetPath);
                //传一个URL给前端
                String fileUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                        .path("/photo/webImage/")
                        .path(folderName)
                        .path("/")
                        .path(filename)
                        .toUriString();

                // 创建文件信息对象，并添加到数组中
                filePaths.add(fileUrl);
            } catch (IOException e) {
                e.printStackTrace();
                return new ResponseEntity<>("文件上传失败！", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }

        return ResponseEntity.ok(filePaths);
    }

}
